<script setup lang="ts">
import {computed, reactive, watch} from 'vue';
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import {$t} from '@/locales';
import {fetchSaveTemplate, fetchUpdateTemplate} from "@/service/api/template";
import OperateType = Api.Common.OperateType;

interface Emits {
  (e: 'submitted'): void;
}

interface Props {
  operateType: OperateType;
  rowData?: Api.Entity.Template | null;
}

defineOptions({
  name: 'TemplateOperateDrawer'
});

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();
const title = computed(() => {
  const titles: Record<Api.Common.OperateType, string> = {
    add: '添加',
    edit: '修改'
  };
  return titles[props.operateType];
});
const model: Api.Entity.Template = reactive(createDefaultModel());
const rules: Record<keyof Pick<Api.Entity.Template, 'name'>, App.Global.FormRule> = {
  name: defaultRequiredRule,
};

function createDefaultModel(): Api.Entity.Template {
  return {
    id: null,
    name: '',
    company: null,
    flowData: {},
    formData: {},
    tableData: {},
    role: [],
  };
}

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }
  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (props.operateType === 'add') {
    let {error} = await fetchSaveTemplate(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
    }
  }
  if (props.operateType === 'edit') {
    let {error} = await fetchUpdateTemplate(model);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
    }

  }
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="模板名称" path="name">
          <NInput v-model:value="model.name" placeholder="请输入模板名称"/>
        </NFormItem>
        <NFormItem label="是否使用中">
          <n-switch size="small" v-model:value="model.isDefault"/>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
